package com.chagee.store.operation.server.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.alibaba.fastjson.JSONValidator.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author: chang.jiawei
 * @date: 2024/01/31
 */
@Slf4j
public class SerializeUtil implements RedisSerializer<Object> {

	static final byte[] EMPTY_ARRAY = new byte[0];
	private final Charset charset;

	public SerializeUtil() {
		this(StandardCharsets.UTF_8);
	}

	public SerializeUtil(Charset charset) {
		Assert.notNull(charset);
		this.charset = charset;
	}

	@Override
	public byte[] serialize(Object object) {  //序列化方法
		try {
			String jsonString = JSONObject.toJSON(object).toString();
			return (jsonString == null ? EMPTY_ARRAY : jsonString.getBytes(charset));
		} catch (Exception e) {
			log.error("redis序列化失败", e);
			throw e;
		}
	}

	@Override
	public Object deserialize(byte[] bytes) throws SerializationException { //反序列化
		if (bytes == null) {
			return null;
		}
		Object object;
		try {
			String objectStr = new String(bytes, charset); //byte数组转换为String
			JSONValidator validator = JSONValidator.from(objectStr);
			Type type = validator.getType();
			if (type == Type.Object) {
				object = JSONObject.parseObject(objectStr);  //返回的是JSONObject类型  取数据时候需要再次转换一下
			} else {
				object = objectStr;
			}
		} catch (Exception e) {
			log.error("redis反序列化失败", e);
			throw e;
		}
		return object;
	}
}
